<?php
/**
 * Created by PhpStorm.
 * User: dt
 * Time: 16:53
 */
namespace backend\base;

use backend\models\AdminRolePermissionModel;
use backend\models\OrganizationModel;
use backend\models\PermissionModel;
use backend\models\SystemOperateRecordModel;
use yii\web\Controller;
use Yii;
use yii\base\Exception;


/**
 * 控制器基类
 * @package app\base
 */
class BaseController extends Controller
{
    //存储request请求体
    public $body = [];
    //存储data
    public $data = [];
    public $title;
    //权限列表
    public $permission_url = [];

    public function beforeAction($action){
        $controller_id = Yii::$app->controller->id;
        $action_id = Yii::$app->controller->action->id;
        //验证权限
        $auth_res = $this->userAuth($controller_id, $action_id);
        if ($auth_res !== true) {
            //没有登录
            if($auth_res == 'no_login'){
                $this->redirect(['site/index']);
            //没有权限
            }else if($auth_res == 'no_auth'){
                if(Yii::$app->request->isAjax){
                    echo json_encode(self::ajaxReturn('auth_error'));
                }else{
                    $this->redirect(['site/auth-error']);
                }
            }
            return false;
        }
        $this->body();
        //不是ajax
        if(!Yii::$app->request->isAjax){
            //记录来源
            $this->saveReferrer();
            //菜单列表
            if(!Yii::$app->request->isAjax){
                if(!Yii::$app->user->isGuest) {
                    $menu = Yii::$app->cache->get(Yii::$app->user->identity->id . 'abcd' . Yii::$app->user->identity->username);
                    if (!empty($menu)) {
                        $this->view->params['menu'] = json_decode($menu, true);
                    } else {
                        $menu = $this->getMyMenu();
                        Yii::$app->cache->set(Yii::$app->user->identity->id . 'abcd' . Yii::$app->user->identity->username, json_encode($menu), 60 * 60);
                        $this->view->params['menu'] = $menu;
                    }
                }else{
                    $menu = $this->getMyMenu();
                    $this->view->params['menu'] = $menu;
                }
            }
        }
        $this->view->params['oss_root_domain'] = Yii::$app->params['oss']['root_domain'];
       return true;
    }

    /*
     * 用户访问权限验证
     * @param $controller
     * @param $action
     */
    protected function userAuth($controller,$action){
        $url = "$controller/$action";
        //不需要登录
        $guest_rules = [
            'site/login','site/logout','site/index','site/get-agent-area','site/forget-pass','site/kds-upload-video','site/upload-video','site/get-oss-upload',
            'site/refresh-upload-video','teacher/search-list-ajax-do','organization/search-list-ajax-do','user/search-list-ajax-do',
            'course/search-list-ajax-do','course/search-tags-list-ajax-do','agent/search-list-ajax-do'
        ];
        //不需要权限
        $login_rules = [
            'site/update-password','site/demo','site/auth-error','site/sort-edit','site/getarea','site/get-video-play-auth',
            'course-class/get-class-ajax-do','course/get-child-list'
        ];
        if(in_array($url,$guest_rules)){
            return true;
        }
        //游客,没权限
        if(Yii::$app->user->isGuest){
            return 'no_login';
        }
        //超级管理员,所有权限
        if(Yii::$app->user->id == 1){
            return true;
        }
        //不需要权限
        if(in_array($url,$login_rules)){
            return true;
        }
        $auth = AdminRolePermissionModel::checkAuth(Yii::$app->user->identity->role_id,$url);
        if(!$auth){
            return 'no_auth';
        }
        return true;
    }

    /*
     * 返回信息处理
     */
    public static function ReturnData($str,$data=[])
    {
        return json_encode(self::ajaxReturn($str, $data));
    }

    /*
     * 权限查询
     */
    public static function orgSelect($model)
    {
        if(Yii::$app->user->identity->account_type != 1 && Yii::$app->user->id != 1){
            $org = OrganizationModel::find()->select(['id'])->where(['user_id'=>Yii::$app->user->id])->asArray()->all();
            $model->andWhere(['in','organization_id',array_column($org,'id')]);
        }
    }

    /**
     * 获取我的菜单列表
     * @return array
     */
    protected function getMyMenu(){
//        $menu = Yii::$app->params['menu'];
        $menu = PermissionModel::levelList();
        if(!$menu || Yii::$app->user->isGuest){
            return [];
        }
        if(Yii::$app->user->id == 1){
            return $menu;
        }
        $permission = AdminRolePermissionModel::findOne(['role_id'=>Yii::$app->user->identity->role_id]);
        $menu_code = explode(',',$permission->permission_codes);
        if(!$menu_code){
            return [];
        }
        $menu = self::resetMenu($menu,$menu_code);
        return $menu;
    }

    public function resetMenu($menu,$menu_code)
    {
        foreach($menu as $k => $v){
            if(!in_array($v['code'],$menu_code)){
                unset($menu[$k]);continue;
            }
            if(!empty($v['child'])){
                $menu[$k]['child'] = self::resetMenu($v['child'],$menu_code);
            }
        }
        return $menu;
    }

    /**
     * list来源记录
     */
    protected function saveReferrer(){
        $referrer = Yii::$app->request->referrer;
        if($referrer){
            $referrer_info = parse_url($referrer);
            if(isset($referrer_info['path'])){
               $str = strrchr($referrer_info['path'],'/');
                if($str && strpos($str,'list') !== false){
                    Yii::$app->session->setFlash('list_referrer_url',$referrer);
                }
            }
        }
    }
    /**
     * 保存后跳转回list页面
     */
    protected function saveBack($default = 'list'){
        $list_referrer_url = Yii::$app->session->getFlash('list_referrer_url');
        if($list_referrer_url){
            return $this->redirect($list_referrer_url);
        }
        return $this->redirect($default);
    }

    /**
     * 权限url判断当前用户权限
     * @param string $url
     * @return bool
     */
    public function isAuth($url = '')
    {
        if(Yii::$app->user->id == 1){
            return true;
        }
        if(!$url || !Yii::$app->user->id){
            return false;
        }
        if(in_array($url,$this->permission_url)){
            return true;
        }
        return false;
    }

    /**
     * 添加操作记录
     */
    public function addRecord($title,$id)
    {
        $model = new SystemOperateRecordModel();
        $model->desc = $title.'->'.$id;
        $model->save();
    }

    /***
     * 存储body体与data数据
     * @return bool
     */
    protected function body()
    {
        if(Yii::$app->request->isPost){
            $this->body=Yii::$app->request->post();
            return true;
        }
        if(Yii::$app->request->isGet){
            $this->body=Yii::$app->request->get();
            return true;
        }
        return false;
    }

    /**
     * 统一JSON返回
     * @param $errIndex
     * @param array $data
     * @return array
     * @throws Exception
     */
    protected function ajaxReturn($errIndex, $data = [])
    {
        if (empty(Yii::$app->params[$errIndex])) {
            $errorMsg = json_encode([
                'code' => Yii::$app->params['params_error']['code'],
                'message' => "未找到返回信息索引[{$errIndex}]",
                'data' => [],
            ],JSON_UNESCAPED_UNICODE);
            throw new Exception($errorMsg);
        }
        $error = Yii::$app->params[$errIndex];
        return [
            'code' => $error['code'],
            'message' => $error['info'],
            'data' => $data
        ];
    }

    /*
     * 统一返回自定义错误信息
     * @param $errIndex
     * @param array $data
     * @return array
     * @throws Exception
     */
    public static function ajaxCustom($code='80000', $error='',$data = [])
    {
        return json_encode([
            'code' => $code,
            'message' => $error,
            'data' => $data
        ]);
    }

    /**
     * 数据安全处理
     * @param     array/string    $data    需要处理的数据
     * @return    array/string    $data    处理后的数据
     */
    public static function parseData($data)
    {
        if(is_array($data)){
            foreach ($data as $k => $v) {
                if(is_array($v)){
                    $data[$k] = self::parseData($v);
                }else if (is_string($v)) {
                    $data[$k] = trim(htmlspecialchars(addslashes($v)));
                }
            }
        }else if (is_string($data)) {
            $data = trim(htmlspecialchars(addslashes($data)));
        }
        return $data;
    }

    public function get($name,$default=null){
        return Yii::$app->request->get($name,$default);
    }
    public function post($name,$default=null){
        return Yii::$app->request->post($name,$default);
    }

    public function getJavaData($url,$data){
        $data['operatorId'] = Yii::$app->user->getId();
    }

    /**
     * 二维数组根据字段进行排序
     * @params array $array 需要排序的数组
     * @params string $field 排序的字段
     * @params string $sort 排序顺序标志 SORT_DESC 降序；SORT_ASC 升序
     */
    function arraySequence($array, $field, $sort = 'SORT_DESC')
    {
        $arrSort = array();
        foreach ($array as $uniqid => $row) {
            foreach ($row as $key => $value) {
                $arrSort[$key][$uniqid] = $value;
            }
        }
        array_multisort($arrSort[$field], constant($sort), $array);
        return $array;
    }

    /*
     * 二维数组去重
     */
    public function assoc_unique($arr, $key) {
        $tmp_arr = array();
        foreach ($arr as $k => $v) {
            if (in_array($v[$key], $tmp_arr)) {//搜索$v[$key]是否在$tmp_arr数组中存在，若存在返回true
                unset($arr[$k]);
            } else {
                $tmp_arr[] = $v[$key];
            }
        }
        sort($arr); //sort函数对数组进行排序
        return $arr;
    }

}